package dhy.com.config.protocol;

import dhy.com.message.Message;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.List;

/**
 * <P>
 *     消息的编解码器
 * </P>
 * @author zdh
 */
@Slf4j
public class MessageCodec extends ByteToMessageCodec<Message> {

    /**
     * <P>
     *     消息编码器
     * </P>
     * @param ctx
     * @param msg
     * @param out
     * @throws Exception
     */
    @Override
    public void encode(ChannelHandlerContext ctx, Message msg, ByteBuf out) throws Exception {
        // 1. 4 字节的魔数
        out.writeBytes(new byte[]{1, 2, 3, 4});
        // 2. 1 字节的版本,
        out.writeByte(1);
        // 3. 1 字节的序列化方式 jdk 0 , json 1
        out.writeByte(0);
        // 4. 1 字节的指令类型
        out.writeByte(msg.getMessageType());
        // 5. 4 个字节
        out.writeInt(msg.getSequenceId());
        // 无意义，对齐填充 ---一般都是16的整数倍
        out.writeByte(0xff);
        // 6. 获取内容的字节数组
        //这里假定使用jdk序列化方式写出数据
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(msg);
        byte[] bytes = bos.toByteArray();
        // 7. 长度
        out.writeInt(bytes.length);
        // 8. 写入内容
        out.writeBytes(bytes);
    }

    /**
     * <P>
     *     消息解码器
     * </P>
     * @param ctx
     * @param in
     * @param out
     * @throws Exception
     */
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        //1.读取魔数
        int magicNum = in.readInt();
        //2.版本
        byte version = in.readByte();
        //3.序列化方式
        byte serializerType = in.readByte();
        //4.指令类型
        byte messageType = in.readByte();
        //5.消息的序号
        int sequenceId = in.readInt();
        //6.读取填充字节---无意义
        in.readByte();
        //7.读取数据长度
        int length = in.readInt();
        byte[] bytes = new byte[length];
        //8.按照指定长度读取数据
        in.readBytes(bytes, 0, length);
        //序列化方式读取出数据
        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
        Message message = (Message) ois.readObject();
        log.debug("{}, {}, {}, {}, {}, {}", magicNum, version, serializerType, messageType, sequenceId, length);
        log.debug("{}", message);
        //将解码后的数据加入消息集合
        out.add(message);
    }
}